package com.sline.Test;

import java.io.*;
import java.net.Socket;
import java.nio.Buffer;
import java.util.Scanner;

public class Demo2_FileTransferClient {
    public static void main(String[] args) throws IOException {

        File file = getFile();

        Socket socket = new Socket("127.0.0.1",2233);

        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintStream ps = new PrintStream(socket.getOutputStream());

        ps.println(file.getName());

        String result = br.readLine();
        System.out.println("客户端收到结果" + result);
        if ("存在".equals(result)) {
            System.out.println("您上传的文件已经存在, 请不要重新上传");
            socket.close();
            return;
        }

        System.out.println("开始上传");

        FileInputStream fis = new FileInputStream(file);
        byte[] arr = new byte[8192];
        int len;

        while ((len = fis.read(arr)) != -1) {
            ps.write(arr, 0, len);
        }

        fis.close();
        socket.close();
    }

    public static File getFile() {
        Scanner sc = new Scanner(System.in);

        while (true) {
            String line = sc.nextLine();
            File file = new File(line);

            if (!file.exists()) {
                System.out.println("您输入的文件不存在, 请重新输入");
            } else if (file.isDirectory()) {
                System.out.println("您输入的路径是文件夹, 请重新输入");
            } else if (file.isFile()) {
                return file;
            } else {
                System.out.println("您输入的信息有误, 请重新输入");
            }
        }
    }
}
